package com.example.netty.server;

import com.example.netty.init.SimpleChatServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author PC
 */
public class ChatServer {
    private final static Logger logger = LoggerFactory.getLogger(ChatServer.class);

    public void run() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //bossGroup处理服务器的接收连接，workerGroup处理已接受连接的I/O操作
            serverBootstrap.group(bossGroup, workerGroup)
                    //使用nio通道处理tcp连接
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new SimpleChatServerInitializer())
                    //tcp队列中等待接受的最大连接数
                    .option(ChannelOption.SO_BACKLOG, 128)
                    //启用保活
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            //绑定18080端口启动netty服务
            ChannelFuture channelFuture = serverBootstrap.bind(18080).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
            logger.info("服务端关闭了");
        }
    }

    public static void main(String[] args) {
        new ChatServer().run();
    }
}
